<template>
  <div class="app-container table-app-container">
    <div v-loading="uploading" class="fixed-table">
      <div class="fixed-table-actionbar">
        <table-filter />
        <action-bar @on-before-upload="onBeforeUpload" @on-success-upload="onSuccessUpload" @on-fail-upload="onFailUpload" />
      </div>
      <PageableTable
        :loading="loading"
        :data="insideTableData"
        :total="totalElements"
        :page="currentPage"
        :page-size="pageSize"
        :table-height="tableHeight"
        class="fixed-table-table"
        :multiple-selected="true"
        @page-change="onPageChange"
        @sort-change="onSortChange"
        @selection-change="onSelectionChange"
      >

        <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button title="编辑" type="text" size="mini" icon="el-icon-edit" @click="edit(row.id)" />
            <el-button v-if="row.username !== 'admin'" title="删除" type="text" size="mini" icon="el-icon-delete" @click="remove(row.id)" />
          </template>
        </el-table-column>
      </PageableTable>
    </div>
    <FormDialog
      title="编辑"
      :show.sync="dialogFormVisible"
      width="60%"
      @on-ok="ok"
      @on-cancel="cancel"
    >
      <EditForm :id="editId" ref="editForm" />
    </FormDialog>
  </div>
</template>

<script>
// tableHeight属性，从mixin混入而来
// secondary package based on el-pagination
import FormDialog from '@neu/biz-core/components/FormDialog'
// 表格查询组件独立编写，需要传递pageable-table实例的mixin方法filter
import TableFilter from './components/tableFilter'
// 编辑实例组件独立编写，需要传递id属性，判断新建还是更新操作
import EditForm from './components/editForm'
import ActionBar from './components/actionBar'
import PageableTable from '@neu/biz-core/components/PageableTable'

import { page, remove } from '@neu/dcvm-ui/api/model'
import databind from '@neu/biz-core/mixins/databind'
import { downloadFileUrl } from '@neu/dcvm-ui/api/file'
import { listOfType } from '@neu/dcvm-ui/api/dictionary'

export default {
  name: 'UsersPage',
  components: {
    TableFilter,
    FormDialog,
    EditForm,
    ActionBar,
    PageableTable
  },
  mixins: [databind],
  data() {
    return {
      r: page,
      d: remove,
      insideColumns: [
        { title: '模具名', key: 'modelName' },
        { title: '模具编码', key: 'modelCode' },
        {
          title: '模具类别',
          key: 'typeId',
          render: (h, params) => {
            const type = this.availableModelTypes.find(it => it.code === params.row.typeId)
            if (type) {
              return (<span>{type.text}</span>)
            } else {
              return (<span>{params.row.typeId}</span>)
            }
          }
        },
        { title: '长度', key: 'length' },
        { title: '宽度', key: 'width' },
        { title: '高度', key: 'height' },
        {
          title: '预览',
          key: 'fsId',
          render: (h, params) => {
            if (params.row.imgUrl) {
              return (
                <el-image src={this.fileUrl(params.row.imgUrl)} previewSrcList={[this.fileUrl(params.row.imgUrl)]} fit='contain' class='avatar' style='height: 48px; width: 48px' />
              )
            } else {
              return (
                <span />
              )
            }
          }
        },
        {
          title: '3D文件',
          key: 'versionList',
          render: (h, params) => {
            if (params.row.versionList.length > 0) {
              const div = <div>
                {
                  params.row.versionList.map((item, idx) => {
                    return (<div><a href={this.fileUrl(item.fileUrl)} download title={item.fileName}>{item.versionCode}</a></div>)
                  })
                }
              </div>
              return div
            } else {
              return (<div></div>)
            }
          }
        }
      ],
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        update: '编辑',
        create: '新建'
      },
      availableModelTypes: [],
      editId: -1,
      uploading: false
    }
  },
  created() {
    listOfType('modelType').then(response => {
      this.availableModelTypes = response.data
    })
    this.filter()
  },
  methods: {
    // responseFormatter(result) {
    //   return result.filter(it => it.username !== 'admin')
    // },
    edit(id) {
      // 更新当前被编辑实体的ID，自动传递至编辑表单
      this.editId = id
      // 打开对话框
      this.dialogFormVisible = true
    },
    ok() {
      // 直接调用表单实例的保存方法
      this.$refs.editForm.save().then(response => {
        if (response === false) return
        this.$message({
          showClose: true,
          message: '操作成功！',
          type: 'success'
        })
        // 调用pageable-table实例的mixin方法refresh()，更新表格
        this.refresh()
        // 关闭对话框
        this.dialogFormVisible = false
      })
    },
    cancel() {
      this.editId = -1
      // this.$refs.editForm.reset()
      this.dialogFormVisible = false
    },
    fileUrl(fsId) {
      return downloadFileUrl(fsId)
    },
    onBeforeUpload() {
      this.uploading = true
    },
    onSuccessUpload(count) {
      this.uploading = false
      this.refresh()
      this.$message({
        showClose: true,
        message: '上传成功（' + count + '）',
        type: 'success'
      })
    },
    onFailUpload(error) {
      this.uploading = false
      this.$message({
        showClose: true,
        message: error,
        type: 'error'
      })
    }
  }
}
</script>
